package com.javaxiaobear.base.framework.security.service;

import com.javaxiaobear.base.common.enums.UserStatus;
import com.javaxiaobear.base.common.exception.ServiceException;
import com.javaxiaobear.base.common.utils.MessageUtils;
import com.javaxiaobear.base.common.utils.SecurityUtils;
import com.javaxiaobear.base.common.utils.StringUtils;
import com.javaxiaobear.base.framework.security.BadCredentialsException;
import com.javaxiaobear.base.framework.security.LoginUser;
import com.javaxiaobear.module.system.domain.SysUser;
import com.javaxiaobear.module.system.service.ISysUserService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.stereotype.Service;

/**
 * 用户验证处理
 *
 * @author javaxiaobear
 */
@Service
@Slf4j
public class UserDetailsService {

  @Resource ISysUserService userService;

  @Resource SysPasswordService passwordService;

  @Resource SysPermissionService permissionService;

  public LoginUser loadUserByUsername(String username, String password) {
    SysUser user = userService.selectUserByUserName(username);
    if (StringUtils.isNull(user)) {
      log.info("登录用户：{} 不存在.", username);
      throw new ServiceException(MessageUtils.message("user.not.exists"));
    } else if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
      log.info("登录用户：{} 已被删除.", username);
      throw new ServiceException(MessageUtils.message("user.password.delete"));
    } else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
      log.info("登录用户：{} 已被停用.", username);
      throw new ServiceException(MessageUtils.message("user.blocked"));
    }

    passwordService.validate(user, username, password);

    return createLoginUser(user);
  }

  public LoginUser createLoginUser(SysUser user) {
    return new LoginUser(
        user.getUserId(), user.getDeptId(), user, permissionService.getMenuPermission(user));
  }

  public LoginUser login(String username, String password) {
    val user = loadUserByUsername(username, password);
    if (!SecurityUtils.matchesPassword(password, user.getPassword())) {
      throw new BadCredentialsException("密码不正确");
    }
    SecurityUtils.login(user);
    return user;
  }
}
